import time
import csv
from selenium import webdriver
from write_csv import write_csv
from logo_text import write_csv

# import модуля для работы с выпадающими списками
from selenium.webdriver.support.select import Select

# https://pypi.org/project/webdriver-manager/
from webdriver_manager.chrome import ChromeDriverManager


def time_watcher():  # таймер скорости исполнения
    print('--- %s seconds ---' % (time.time() - start_time))


def get_data(browser, url):
    browser.get(url)
    path_1 = '//*[@id="name_list"]/div[1]/div[2]/div/div[3]/div[2]/select'
    path_2 = '//*[@id="name_list"]/div[1]/div[2]/div/div[4]/div[2]/select'
    path_3 = '//*[@id="name_list"]/div[1]/div[2]/div/div[5]/div[2]/select'
    path_4 = '//*[@id="name_list"]/div[1]/div[2]/div/div[6]/div[2]/select'
    path_button = '//*[@id="name_list"]/div[1]/div[2]/div/div[1]/div/div'

    select_1 = browser.find_element_by_xpath(path_1)
    select_2 = browser.find_element_by_xpath(path_2)
    select_3 = browser.find_element_by_xpath(path_3)
    select_4 = browser.find_element_by_xpath(path_4)

    # зададим отсрочку 5 сек
    t = 1

    # задаём поведение select'ов
    # Select(select_1).select_by_value("1")  # отбор по значению
    Select(select_1).select_by_visible_text("Общий конкурс")  # отбор по тексту
    time.sleep(t)
    Select(select_2).select_by_value("1")
    time.sleep(t)
    Select(select_3).select_by_value("87")
    time.sleep(t)
    Select(select_4).select_by_value("2")

    # обработка клика по кнопке
    browser.find_element_by_xpath(path_button).click()
    # обязательно ставить отсрочку, чтобы успела подгрузиться таблица
    time.sleep(t)

    # получение DOM-страницы после выбора select'ов и нажатия button
    # html = browser.page_source

    trs = browser.find_element_by_tag_name(
        'tbody').find_elements_by_class_name('entrant-success')

    for tr in trs:
        tds = tr.find_elements_by_tag_name('td')
        try:
            _id = tds[0].text.strip()
        except:
            _id = ''
        try:
            num = tds[1].find_element_by_tag_name('nobr').text.strip()
        except:
            num = ''
        try:
            name = tds[2].find_element_by_tag_name('span').text.strip()
        except:
            name = ''
        try:
            summ = tds[7].text.strip()
        except:
            summ = ''

        data = {
            "id": _id,
            "num": num,
            "name": name,
            "sum": summ,
        }
        order = ["id", "num", "name", "sum"]
        # write_csv(data, order)
        print(data)

    browser.close()
    time_watcher()


def main():
    url = 'https://pk.mipt.ru/bachelor/list/'
    browser = webdriver.Chrome(executable_path=ChromeDriverManager().install())
    browser.maximize_window()  # увеличиваем окно для удобства
    get_data(browser, url)
    logo_text(browser, url)


start_time = ''
if __name__ == '__main__':
    start_time = time.time()
    main()
